<template>
  <div class="flow" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="query" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search(1)'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="source">
                  <span class = "condi">{{$t('report.imReportFrom')}}</span>
                  <m7Select class="el-select" filterable multiple :options="fromUrlList" v-model="fromUrl" :defaultProps="showObj"></m7Select>
                </div>
                <div class="source">
                  <el-row>
                    <el-col class="condi">
                      <span>{{$t('report.imReportArea')}}</span>
                    </el-col>
                    <el-col :span="10" class="provin">
                      <el-select size="mini"
                             v-model.trim="area"
                             multiple
                             filterable
                             :placeholder="$t('report.pleasePro')">
                        <el-option v-for="(item, index) in province"
                                   :label="item"
                                   :value="item"
                                   :key="index"></el-option></el-select>
                    </el-col>
                  </el-row>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <el-button class="primary_btn fr set_header" v-on:click.stop="config" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>
          <el-button class="primary_btn fr turnCha" @click.stop="changeHighChartsType">{{chart}}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportExcel"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportExcel"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
          <el-button class="primary_btn fr pdf" @click.stop="exportReportTask">{{$t('customer.exportTaskList')}}</el-button>
        </div>
        <div class="deploy">
          <!-- <i class="iconfont icon-peizhi"></i>
          <span class="tex" @click.stop="config">{{$t('report.setHeaderConfig')}}</span> -->
          <div class="search-pagination">
            <pagination
                :small="paginationRecord.small"
                :currentPage="paginationRecord.currentPage"
                :count="countRecord"
                :num="paginationRecord.num"
                @turnPage="turnPageRecord"
                :totalPage="totalPageRecord"
                >
            </pagination>
          </div>
          <span class="tex fr">{{$t('report.totalRecord', {countNum: countNum})}}</span>
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                {{$t('report.imReportIPNum')}}<br>
                {{$t('report.imReportPVCount')}}<br>
                {{$t('report.imReportUVCount')}}<br>
                {{$t('report.imNewVisiteNum')}}<br>
                {{$t('report.imAverLookNum')}}<br>
                {{$t('report.imReportClickNum')}}<br>
                {{$t('report.imReportLeaveNum')}}<br>
                {{$t('report.imAverVisiteTime')}}<br>
                {{$t('report.imAverVisitePage')}}<br>
                {{$t('report.imSearchKeyWords')}}<br>
                {{$t('report.imSearchNum')}}<br>

              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="tableData" :sum="totalData" :config="headOptions.Config"></report-table>
      </div>
    </div>
    <export-count-down @close="close" :isDialogVisible="isDialogVisible"></export-count-down>
    <el-dialog modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <header-option v-show="isHeaderConfigShow" :show="isHeaderConfigShow" :option="headOptionsShow" :type="id" v-on:close="closeHeader"></header-option>
  </div>
</template>
<script>
  import affix from '../../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../../ui-modules/unfold/index.vue'
  import exportCountDown from '../../base/exportCountDown.vue'
  import dateTime from '../../base/datetime.vue'
  import headerOption from '../../base/headerOption.vue'
  import reportTable from '../../base/reportTable.vue'
  import { deepClone, optionTimeTypeCheck, getFormatTimeBySecond } from '@/utils/m7Utils.js'
  import { exportReportPdf, headOptionsToXlsxHeaders, checkTime, searchTime, colorConfigArr, sortDataByKey, exportNum } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import Pagination from '@/components/public-modules/card/Pagination'

  export default {
    name: 'flow',
    data () {
      return {
        isDialogVisible: false, // 是否展示倒计时
        showObj: {
          value: '_id',
          label: 'urlTitle'
        },
        isFold: false,
        headOptionsShow: {},
        isHeaderConfigShow: false,
        fromUrl: [],
        area: [],
        province: ['上海', '浙江', '西沙群岛', '澳门', '台湾', '甘肃', '香港', '宁夏', '陕西', '安徽', '湖北', '广东', '福建', '北京', '河北', '山东', '天津', '江苏', '海南', '青海', '吉林', '西藏', '新疆', '河南', '内蒙古', '黑龙江', '云南', '广西', '辽宁', '四川', '重庆', '贵州', '湖南', '山西', '江西'],
        chart: this.$t('report.imReportLine'),
        selectedAgentList: [],
        fromUrlList: [],
        id: 'im_keyword_report_traffic',
        title: this.$t('report.imFlowAnalysis'),
        paginationRecord: { // 翻页组件传入的数据
          currentPage: 1,
          small: 'small',
          num: 20
        },
        countRecord: 0, // 当前页
        totalPageRecord: 1, // 共有多少页
        countNum: 0, // 共有多少条记录
        loading: false,
        timeType: 'day',
        query: {
        },
        dialogVisible: false,
        serverData: [],
        headOptions: { Config: [], data: [] },
        highchartsDefaultOptions: {
          chart: {
            type: 'column',
            animation: false
          },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: {
            text: this.$t('report.imFlowAnalysis')
          },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      headerOption,
      Pagination,
      exportCountDown
    },
    computed: {
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      tableData () {
        return this.getTableData(this.serverData, this.headOptions)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let headerConfig = this.headOptions.Config || []
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'averageAccessLength' || item.name === 'visitorLossRate' || item.name === 'seoKeywords') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(datas[i]._id)
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(datas[i][seriesArray[j].valueName] || 0)
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray
        return options
      },
      totalData () {
        return this.getTotalData(this.serverData, this.headOptions)
      }
    },
    methods: {
      close (data) {
        if (data === 'export') {
          this.exportReportTask()
        }
        this.isDialogVisible = false
        console.log(88888)
      },
      // 路由跳转到导出任务列表
      exportReportTask () {
        this.$router.push({
          path: '/index/report/report_export',
          query: {
            isExport: true
          }
        })
      },
      // 翻页查询方法 参数当前请求页数
      turnPageRecord (pageNum) {
        this.paginationRecord.currentPage = pageNum
        this.search(pageNum, true)
      },
      getTableData (serverData, headOptions) {
        if (!serverData || serverData.length === 0) {
          return []
        }
        let data = deepClone(serverData)
        let userVisitCountSum = 0
        let pageVisitCountSum = 0
        data.forEach(item => {
          if (item.pageVisitCount) {
            pageVisitCountSum += item.pageVisitCount
          }
          if (item.userVisitCount) {
            userVisitCountSum += item.userVisitCount
          }
        })
        headOptions.Config.forEach(item => {
          data.forEach(obj => {
            obj[item.name] = obj[item.name] || 0
            if (item.name === 'averageAccessLength') {
              obj[item.name] = getFormatTimeBySecond(obj[item.name])
            }
            if (item.name === 'visitorLossRate') {
              obj[item.name] = `${obj[item.name]}%`
            }
            if (item.name === 'searchKeywordProportion') {
              obj[item.name] = userVisitCountSum > 0 ? Math.round(obj.userVisitCount / userVisitCountSum * 100) + '%' : '0%'
            }
            if (item.name === 'searchountProportion') {
              obj[item.name] = pageVisitCountSum > 0 ? Math.round(obj.pageVisitCount / pageVisitCountSum * 100) + '%' : '0%'
            }
          })
        })
        data = sortDataByKey(data, 'seoKeywords', 'string')
        return data
      },
      getTotalData (serverData, headOptions) {
        if (!serverData || serverData.length === 0) {
          return [{reportTime: this.$t('report.total')}]
        }
        let headerConfig = headOptions.Config || []
        let datas = serverData
        let userVisitCountSum = 0
        let pageVisitCountSum = 0
        datas.forEach(item => {
          if (item.pageVisitCount) {
            pageVisitCountSum += item.pageVisitCount
          }
          if (item.userVisitCount) {
            userVisitCountSum += item.userVisitCount
          }
        })
        let total = {
          seoKeywords: this.$t('report.total'),
          newPageCount: 0,
          loadTimeLength: 0
        }
        for (let j = 0; j < datas.length; j++) {
          if (datas[j].newPageCount) {
            total.newPageCount += datas[j].newPageCount
          }
          if (datas[j].loadTimeLength) {
            total.loadTimeLength += datas[j].loadTimeLength
          }
        }
        for (let i = 0; i < headerConfig.length; i++) {
          if (headerConfig[i].name === 'seoKeywords') {
            continue
          }
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }
          }
        }
        total.averageVisitView = total.userVisitCount ? Math.round(total.pageVisitCount / total.userVisitCount) : 0
        total.averagePageView = total.userVisitCount ? Math.round(total.newPageCount / total.userVisitCount) : 0
        total.visitorLossRate = total.userLeaveCount ? Math.round(total.userLeaveCount / total.userVisitCount * 100) + '%' : '0%'
        total.averageAccessLength = total.userVisitCount ? getFormatTimeBySecond(Math.round(total.loadTimeLength / total.userVisitCount)) : '00:00:00'
        total.searchKeywordProportion = userVisitCountSum > 0 ? '100%' : '0%'
        total.searchountProportion = pageVisitCountSum > 0 ? '100%' : '0%'
        return [total]
      },
      isShowFold (bool) {
        this.isFold = bool
      },
      // 获取查询条件
      getSearchQueryData (page, limit, isExport) {
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: {
            reportType: this.id,
            area: this.area,
            fromUrl: this.fromUrl
          },
          page: page || 1,
          limit: limit,
          paging: true
        }
        if (!isExport) {
          this.paginationRecord.currentPage = page
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search (page, isTurnPage) {
        var queryData = this.getSearchQueryData(page, 20)

        if (!queryData) {
          return
        }

        this.$store.dispatch('queryKeywordReport', queryData).then((res) => {
          if (res.success) {
            this.serverData = deepClone(res.data)
            this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
            let count = res.count || 0
            if (count) {
              this.countNum = count
              this.totalPageRecord = Math.ceil(count / 20)
              this.countRecord = count / 2
            } else {
              this.countNum = 0
              this.totalPageRecord = 1
              this.countRecord = 1
            }
            if (!isTurnPage) {
              this.$store.dispatch('getFromUrlList', queryData).then((res) => {
                this.fromUrlList = res.fromUrlList
              })
            }
          }
        })
      },
      exportExcel () {
        var queryData = this.getSearchQueryData(1, exportNum.searchNum, true)
        if (!queryData) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryKeywordReport', queryData).then((res) => {
          this.loading = false
          if (res.count > exportNum.maxExportNum) {
            this.$message.warning(this.$t('report.imReportMoreDateTipErro'))
            return
          }
          if (res.count > exportNum.endExportNum) {
            let data = queryData.query
            this.$store.dispatch('addReportExportTask', data).then((response) => {
              console.log(response, 6666)
            })
            this.isDialogVisible = true
            return
          } else {
            this.exportXlsx(res)
            // if (this.$store.getters.exportFromFront) {
            //   this.exportXlsx(res)
            // } else if (this.$store.getters.exportFromEnd) {
            //   this.exportXls()
            // }
          }
        })
      },
      exportXlsx (res) {
        var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])
        var serverData = deepClone(res.data) || []

        var tableData = this.getTableData(serverData, headOptions)
        var headers = headOptionsToXlsxHeaders(headOptions.Config)
        if (tableData && tableData.length) {
          var sum = this.getTotalData(serverData, headOptions)
          tableData = tableData.concat(sum)
        }

        var dh = XlsxUtil.getDownloadHelper(headers, tableData)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download(this.$t('report.imReportSourceFromKeywords') + timeStamp)
      },
      // exportXlsx () {
      //   var queryData = this.getSearchQueryData(1, 100000000, true)

      //   if (!queryData) {
      //     return
      //   }

      //   this.$store.dispatch('queryKeywordReport', queryData).then((res) => {
      //     if (res.success) {
      //       var serverData = deepClone(res.data)
      //       var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])

      //       var tableData = this.getTableData(serverData, headOptions)

      //       if (tableData && tableData.length) {
      //         var sum = this.getTotalData(serverData, headOptions)
      //         tableData = tableData.concat(sum)
      //       }

      //       var headers = headOptionsToXlsxHeaders(headOptions.Config)

      //       var dh = XlsxUtil.getDownloadHelper(headers, tableData)
      //       var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
      //       dh.download(this.$t('report.imReportSourceFromKeywords') + timeStamp)
      //     }
      //   })
      // },
      changeHighChartsType () {
        if (this.chart === this.$t('report.imReportLine')) {
          this.chart = this.$t('report.imReportBar')
          this.highchartsDefaultOptions.chart.type = 'line'
        } else {
          this.chart = this.$t('report.imReportLine')
          this.highchartsDefaultOptions.chart.type = 'column'
        }
      },
      exportXls () {
        let data = {
          Method: 'exportImKeywordReport',
          Query: {
            reportType: this.id,
            user: this.$store.state.session.user._id,
            area: this.area,
            fromUrl: this.fromUrl
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImSessionTimeReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.webchat') + '关键词流量分析' + searchTime(this.query), id: this.id})
      },
      closeHeader (data) {
        this.isHeaderConfigShow = false
        if (data === 'save') {
          this.search()
        }
      },
      config () {
        this.$store.dispatch('getReportTableHeader', this.id).then((res) => {
          this.headOptionsShow = res
          this.isHeaderConfigShow = !this.isHeaderConfigShow
        })
      }
    },
    beforeMount () {
      this.$nextTick(() => {
        this.search(1)
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .flow
    .provin
      width 600px
    .source
      .el-select
        width 600px
    .el-button
      margin 0 0 0 10px
    .source
      margin 14px 0
      .condi
        width 58px
        display inline-block
        line-height 30px
    .tab
      .deploy
        .tip
          margin-left 0px
        .search-pagination
          float right
          line-height 23px
        .tex
          display inline-block
          margin 2px 10px 0 0
          height 26px
          line-height 26px
        .tex:hover
          color $cf-gray1
</style>
